<template>
  <div class="container" v-if="!loadingStore.loading">
    <star-nav-bar :title="navBarTitle" />
    <div class="detail-container" ref="detailContainerRef" @scroll="handleScroll">
      <order-status
        :order-detail="orderDetail"
        :countdown="countdown"
        @openPopup="openPopup"
        @cancelClick="cancelClick"
        @againClick="againClick"
        @deleteClick="deleteClick"
      />
      <order-info :order-detail="orderDetail" />
      <order-meal :order-detail="orderDetail" />
    </div>
  </div>
  <!-- 支付订单弹窗 -->
  <payment
    :order-detail="orderDetail"
    :amount="orderDetail.amount ? orderDetail.amount : 0"
    :is-popup-visible="paymentPopup"
    :countdown="countdown"
    @close-popup="closePopup"
    @order-detail="getOrderDetail"
  />
</template>
<script setup lang="ts">
import payment from './payment.vue'
import orderStatus from './components/order-status.vue'
import orderInfo from './components/order-info.vue'
import orderMeal from './components/order-meal.vue'
import { phoneFormat } from '@/utils/format'
import { cancelOrderAPI, deleteOrderAPI, getOrderDetailAPI, repetitionOrderAPI } from '@/api/order'
import type { OrderDetailResult } from '@/types/order'
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { getOrderStatus } from './constant'
import { useRoute, useRouter } from 'vue-router'
import { showConfirmDialog } from 'vant'
import 'vant/es/dialog/style'
import { useloadingStore } from '@/stores/modules/loading'
import { throttle } from 'lodash'
const route = useRoute()
const router = useRouter()
const loadingStore = useloadingStore()
// 订单id
const orderId = route.query.orderId
// 订单详情
const orderDetail = ref({} as OrderDetailResult)
// 获取订单详情
const getOrderDetail = async () => {
  try {
    if (orderId) {
      const { data } = await getOrderDetailAPI(+orderId)
      orderDetail.value = data
      if (orderDetail.value.phone) {
        orderDetail.value.phone = phoneFormat(orderDetail.value.phone)
      }
    }
  } catch (error) {
    router.back()
    console.log(error)
  }
}
const navBarTitle = ref('')
// 定义页面滚动到的临界位置
const scrollThreshold = 10
const detailContainerRef = ref<HTMLDivElement | null>(null)
// 监听页面滚动事件
const handleScroll = throttle(() => {
  if (detailContainerRef.value) {
    // console.log(detailContainerRef.value.scrollTop)
    const scrollTop = detailContainerRef.value.scrollTop
    if (scrollTop >= scrollThreshold) {
      navBarTitle.value = `订单${getOrderStatus(orderDetail.value.status)}`
    } else {
      navBarTitle.value = ''
    }
  }
}, 100)
// 当前时间
const currentTime = ref(new Date().getTime())
// 获取下单时间
const orderTime = computed(() => orderDetail.value.orderTime)
// 将15分钟转换为毫秒
const fifteenMinutesInMillis = 15 * 60 * 1000
// 定时器id
const timer = ref<number>()
// 计算下单时间过了15分钟后的时间
const endTime = computed(() => new Date(orderTime.value).getTime() + fifteenMinutesInMillis)
// 计算属性用于实时计算倒计时的显示格式
const countdown = computed(() => {
  const totalSeconds = Math.max(0, Math.floor((endTime.value - currentTime.value) / 1000))
  if (totalSeconds > 0) {
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = Math.floor(totalSeconds % 60)
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  } else {
    return ''
  }
})

// 再来一单，跳转到商家
const againClick = async () => {
  try {
    await repetitionOrderAPI(orderDetail.value.id)
    router.push({
      path: '/business',
      query: { id: orderDetail.value.businessId },
    })
  } catch (error) {
    console.log(error)
  }
}
// 删除订单
const deleteClick = async () => {
  try {
    await deleteOrderAPI(orderDetail.value.id)
    router.back()
  } catch (error) {
    console.log(error)
  }
}
/**
 * 取消订单
 */
const cancelClick = () => {
  try {
    showConfirmDialog({
      message: '确认要取消此订单吗?',
      closeOnClickOverlay: true,
    })
      .then(async () => {
        // on confirm
        await cancelOrderAPI(orderDetail.value.id)
        getOrderDetail()
      })
      .catch(() => {
        // on cancel
      })
  } catch (error) {
    console.log(error)
  }
}
/**
 * 支付订单
 */
// 支付弹窗
const paymentPopup = ref(false)
const openPopup = () => {
  paymentPopup.value = true
}
const closePopup = () => {
  paymentPopup.value = false
}
onMounted(async () => {
  loadingStore.showLoading()
  timer.value = setInterval(() => {
    currentTime.value = new Date().getTime()
  }, 1000)
  // 在组件挂载时添加页面滚动事件监听
  // window.addEventListener('scroll', handleScroll)
  try {
    await getOrderDetail()
  } catch (e) {
    console.log(e)
  }
  loadingStore.hideLoading()
})
// 在组件卸载前移除页面滚动事件监听
onBeforeUnmount(() => {
  clearInterval(timer.value)
  window.removeEventListener('scroll', handleScroll)
})
</script>
<style scoped lang="scss">
.van-nav-bar {
  background: transparent;
}
:deep() {
  .van-dialog__message {
    font-size: var(--font-size-big);
  }
}
.detail-container {
  height: calc(100vh - var(--nav-bar-height));
  flex: 1;
  overflow: auto;
}
</style>
